import { ElMessage, ElMessageBox } from 'element-plus';
import MySender from './MySender'
import MsgCommand from "./enums/MsgCommand"
import userStore from '@/store/user'
import { useRoute, useRouter } from "vue-router";
import MsgTypeEnum from "./enums/MsgTypeEnum"
import MsgStatusEnum from "@/utils/socket/enums/MsgStatusEnum";

import {
    reactive,
} from "vue";

export function useSocket() {

    const chatStatus = reactive({
        roomInfo: {},
        chatPagePath: "/chat", //聊天页面路径
        connectTimer: null as any, //定时器
        connectCount: 1,
    });

    const timeout = 5000; // 超时时间
    const store = userStore();
    const router = useRouter();
    const route = useRoute();

    // 初始化websocket
    const initSocketFun = (userInfo: any): void => {

        // 链接socket
        MySender.getInstance().connect(() => {
            console.log("连接成功...");
            //home页面，过期重连
            if (route?.path === chatStatus.chatPagePath && store.userInfo.userId) {
                console.log("用户续期")
                toUserRenewal(userInfo);
            }

            MySender.getInstance().onMsgReceived = (msgCommand, msg) => {
                msgCommand = msgCommand.replace("Res", "")
                const result = JSON.parse(msg.toString())

                switch (msgCommand) {
                    // 创建房间回调
                    case MsgCommand.CREATE_ROOM:
                        chatStatus.roomInfo = result;
                        store.roomId = result.roomId;
                        store.roomInfo = result;
                        setTimeout(() => {
                            store.isRoomFlag = true
                        }, 100);
                        break;
                    // 登录成功回调
                    case MsgCommand.USER_LOGIN:
                        console.log(result, MsgCommand.USER_LOGIN)
                        // MySender.getInstance().heartbeatLoop();
                        break;
                    case MsgCommand.JOIN_ROOM:
                        console.log(result, MsgCommand.USER_LOGIN)
                        setTimeout(() => {
                            store.isRoomFlag = true
                        }, 100);
                        store.roomInfo = result;
                        break;
                    // 加入房间通知
                    case MsgCommand.JOINROOM_NOTIFY:
                        JoinRoomNotifyFun(result)
                        break;
                    // 同步房间成员
                    case MsgCommand.SYNC_ROOM_MEMBERS:
                        store.personList = result.list
                        break;
                    // 接收广播消息
                    case MsgCommand.SEND_MESSAGE:
                        updateMessageStateFun(result);
                        break;
                    case MsgCommand.BROAD_CASTMESSAGE:
                        console.log(result, MsgCommand.SEND_MESSAGE)
                        syncMessage(result);
                        break;
                    // 异常信息
                    case MsgCommand.EXCEPTIN_MSG:
                        console.log(result, MsgCommand.EXCEPTIN_MSG)
                        ElMessage.error(result.message)
                        if (result.state === 10006 || result.state === 10007) {
                            MySender.getInstance().heartbeatStop();
                            router.replace('/h5/login');
                            //resetAllInfo();
                        }
                        break;
                    // 用户续期
                    case MsgCommand.RENEWAL_USER:
                        userRenewalFun(result);
                        break;
                    // 用户离开房间
                    case MsgCommand.LEAVE_ROOM:
                        leaveRoomInfoFun(result);
                        break;
                    // 其他用户离开房间广播
                    case MsgCommand.LEAVE_ROOM_NOTIFY:
                        console.log(result, MsgCommand.LEAVE_ROOM_NOTIFY)
                        leaveRoomNotifyFun(result)
                        break;
                }
            }
        })

        //关闭socket
        MySender.getInstance().closeService = () => {

            if (chatStatus.chatPagePath === route.path) {
                //尝试重连
                repairSocket(5, userInfo)
            }
            // appStore.setWebsocketStatus(false);
            // AQSender.getInstance().heartbeatStop();
            // loading && loading.close();
        }
    }


    /***
     * 断线重连
     * @param times 重连次数
     * @param userInfo 用户信息
     */
    const repairSocket = (times: number, userInfo: any) => {
        if (null != chatStatus.connectTimer) {
            return false;
        }
        ElMessage.error({
            message: `服务器断开，正在尝试第${chatStatus.connectCount}重连`,
            type: 'warning',
            duration: 0
        })
        chatStatus.connectTimer = setInterval(() => {
            chatStatus.connectCount++;
            //关闭消息弹框
            ElMessage.closeAll();
            ElMessage.error({
                message: `服务器断开，正在尝试第${chatStatus.connectCount}重连`,
                type: 'warning',
                duration: 0
            })
            if (chatStatus.connectCount > times) {
                clearInterval(chatStatus.connectTimer)
                chatStatus.connectTimer = null
                ElMessageBox.confirm("服务已关闭，是否重新登录", "系统提示", {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "warning",
                }).then(res => {
                    router.replace({
                        path: "/login",
                    })
                })
                ElMessage.closeAll();
            }
            initSocketFun(userInfo);
        }, 5000);

    }

    const syncMessage = (msg: any) => {
        //阻塞当前用户消息
        if (msg.user.userId === store.userInfo.userId) return;
        store.messageList.push({
            user: msg.user,
            type: msg.msgType,
            msgStatus: MsgStatusEnum.SUCCESS,
            msg: msg.msg,
            position: store.userInfo.userId.toString() === msg.senderId.toString() ? "right" : "left",
        })
    }

    const userRenewalFun = (result: any) => {
        store.userInfo = result.user;
        if (result.room) {
            store.isRoomFlag = true;
            store.roomInfo = result.room;
            store.personList = result.room.member_list
        }
    }

    const leaveRoomInfoFun = (result: any) => {
        store.isRoomFlag = false
        store.roomInfo = {};
    }


    const leaveRoomNotifyFun = (result: any) => {
        store.messageList.push({
            type: MsgTypeEnum.TIP,
            msgStatus: MsgStatusEnum.SUCCESS,
            msg: `${result.userId}离开了房间`,
        })
    }

    //房间通知
    const JoinRoomNotifyFun = (result: any) => {
        store.messageList.push({
            msgType: MsgTypeEnum.TIP,
            msgStatus: MsgStatusEnum.SUCCESS,
            msg: `${result.userId}加入了房间`,
        })
        setTimeout(() => {
            // 同步房间成员
            MySender.getInstance().sendMsg(MsgCommand.SYNC_ROOM_MEMBERS, {
                roomId: result.roomId,
            });
        }, 100);
    }


    /***
       * 更新消息状态
       */
    const updateMessageStateFun = (msg: any) => {
        debugger    
        if (store.messageList.some(x => x.msgId == msg.msgId)) {
            const info = store.messageList.find(x => x.msgId == msg.msgId);
            info.msgStatus = MsgStatusEnum.SUCCESS;
        }
    }

    //  用户续期
    const toUserRenewal = (userInfo: any) => {
        if (userInfo) {
            MySender.getInstance().sendMsg(MsgCommand.RENEWAL_USER, {
                userId: userInfo.userId,
                userName: userInfo.userName,
                avatar: userInfo.avatar,
            });
        }
    }

    /***
     * 发送网络
     */
    const sendInfoNetWorkFun = (msg: any) => {
        MySender.getInstance().sendMsg(MsgCommand.SEND_MESSAGE, msg);
        //检查发送状态
        store.msgStatusTimer[msg.msgId] = setTimeout(() => {
            if (store.messageList.some(x => x.msgId == msg.msgId)) {
                const info = store.messageList.find(x => x.msgId == msg.msgId);
                if (info.msgStatus == MsgStatusEnum.PENDING) {
                    info.msgStatus = MsgStatusEnum.REJECTED
                }
                // store.messageList = store.messageList.filter(x => x.msgId !== msg.msgId)
            }
        }, timeout);

    }

    /***
   * 发送本地消息
   */
    const sendLocalMsgFun = (msg: any) => {
        store.messageList.push(msg);
    }

    return {
        initSocketFun,
        chatStatus,
        sendInfoNetWorkFun,
        sendLocalMsgFun
    }
}